﻿
using JinYuan.DataConvertLib;
using JinYuan.Helper;
using JinYuan.VirtualDataLibrary;
using MiniExcelLibs;
using System;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace LargeSquareOne
{
    public partial class FrmHistory : Form
    {
        public FrmHistory()
        {
            InitializeComponent();

            this.cmb_SelectType.Items.Add("外观检测进站");
            this.cmb_SelectType.Items.Add("外观检测出站");
            this.cmb_SelectType.SelectedIndex = 0;

            this.dtp_Start.Value = DateTime.Now.AddHours(-2.0f);
            this.dtp_End.Value = DateTime.Now;

            this.cmb_AlarmType.Items.AddRange(new string[] { "全天", "白班", "夜班" });
            this.cmb_AlarmType.SelectedIndex = 0;
        }




        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Query_Click(object sender, EventArgs e)
        {
            string str = this.cmb_SelectType.Text;
            if (string.Compare(str, "外观检测进站") == 0)
            {
                this.cmb_SelectType.SelectedIndex = 0;
            }
            else if (string.Compare(str, "外观检测出站") == 0)
            {
                this.cmb_SelectType.SelectedIndex = 1;
            }
            string barCode = this.txtBarCode.Text.Trim();
            string start = this.dtp_Start.Text;
            string end = this.dtp_End.Text;
            int selectType = this.cmb_SelectType.SelectedIndex;

            Task<OperateResult<DataTable>> task1 = Task.Run(() =>
            {
                return QueryProcess(selectType, barCode, start, end);

            });

            var task2 = task1.ContinueWith(task =>
            {
                this.Invoke(new Action(() =>
                {
                    if (task.Result.IsSuccess)
                    {

                        this.dgv_Main.DataSource = null;

                        this.dgv_Main.DataSource = task.Result.Content;
                    }
                    else
                    {
                        new FrmMsgBoxOutWithAck(2, "查询失败：" + task.Result.Message, "错误提示").Show();
                    }
                }));
            });
        }



        private OperateResult<DataTable> QueryProcess(int selectType, string barCode, string start, string end)
        {
            //判断时间
            DateTime startTime = Convert.ToDateTime(start);
            DateTime endTime = Convert.ToDateTime(end);
            if (startTime > endTime)
            {
                return OperateResult.CreateFailResult<DataTable>("开始时间不能大于结束时间");
            }
            TimeSpan timeSpan = endTime - startTime;
            if (timeSpan.TotalDays > 30.0)
            {
                return OperateResult.CreateFailResult<DataTable>("查询时间不能超过30天");
            }

            DataTable dataTable = CommonMethods.db.QueryDataTable(CommonMethods.dBSQL.SelectHostData(selectType, barCode, start, end));
            if (dataTable != null)
            {
                return OperateResult.CreateSuccessResult<DataTable>(dataTable);
            }
            else
            {
                return OperateResult.CreateFailResult<DataTable>("未能查到数据，请检测");
            }
        }

        private void btn_ExPort_Click(object sender, EventArgs e)
        {



            SaveFileDialog saveFileDialog = new SaveFileDialog();

            saveFileDialog.Filter = "XLSX文件(*.xlsx)|*.xlsx|所有文件|*.*";
            saveFileDialog.Title = "导出历史数据";
            saveFileDialog.FileName = "历史数据" + DateTime.Now.ToString("yyyyMMddHHmmss");
            saveFileDialog.DefaultExt = "xlsx";
            saveFileDialog.AddExtension = true;

            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {

                MiniExcel.SaveAs(saveFileDialog.FileName, this.dgv_Main.DataSource);

                if (new FrmMsgBoxWithAck("导出报表成功，是否立即打开？", "打开报表记录").ShowDialog() == DialogResult.OK)
                {
                    Process.Start(saveFileDialog.FileName);
                }
                else
                {
                    new FrmMsgBoxOutWithAck(2, "导出报表失败", "数据报表导出").ShowDialog();
                }
            }
        }


        /// <summary>
        /// 显示序列号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgv_Main_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            DataGridViewHelper.DgvRowPostPaint((DataGridView)sender, e);
        }

        /// <summary>
        /// 给DataGridView绘制边框
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgv_Main_Paint(object sender, PaintEventArgs e)
        {
            DataGridViewHelper.DgvRowPaint((DataGridView)sender, e, Color.FromArgb(1, 146, 235));
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgv_Main_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.RowIndex != -1 && e.ColumnIndex >= 5)
            {
                object value = this.dgv_Main.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;

                if (value == null || value?.ToString().Length == 0)
                {
                    e.Value = "--";
                }
            }
        }

        #region 减少闪烁
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams parss = base.CreateParams;
                parss.ExStyle |= 0x02000000;
                return parss;
            }
        }
        #endregion



        #region 统计查询
        /// <summary>
        /// 班次
        /// </summary>
        private DataTable dtClasses = null;
        /// <summary>
        /// 日
        /// </summary>
        private DataTable dtDays = null;
        /// <summary>
        /// 周
        /// </summary>
        private DataTable dtWeeks = null;
        /// <summary>
        /// 月
        /// </summary>
        private DataTable dtMonths = null;

        #region 1、按班次查询
        /// <summary>
        /// 按班次查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_ClassQuery_Click(object sender, EventArgs e)
        {
            dtClasses = null;
            DateTime strDate = dtClass.Value;
            string strClass = cmbClass.Text;
            dtClasses = CommonMethods.db.QueryDataTable(CommonMethods.dBSQL.GetStaticByShift(strDate, strClass, CommonMethods.ChangeClassTime));
            if (dtClasses != null && dtClasses.Rows.Count > 0)
            {
                this.dgvClass.DataSource = null;
                this.dgvClass.DataSource = dtClasses;
            }
        }

        /// <summary>
        /// 按班次导出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_ClassExPort_Click(object sender, EventArgs e)
        {
            if (dgvClass.Columns.Count <= 0)
            {
                MessageBox.Show("导出失败，无查询结果");
                return;
            }

            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.FileName = $"产能统计_按班次统计_{DateTime.Now.ToString("yyyyMMddHHmmss")}";
            saveFileDialog.Filter = "*|*.csv";
            if (saveFileDialog.ShowDialog() == DialogResult.Cancel)
                return;

            string msg = "";
            if (CSVHelper<object>.ExportDataTableToCSV(dtClasses, saveFileDialog.FileName, out msg))
            {
                MessageBox.Show("导出成功!");
            }
        }
        #endregion

        # region 2、按日查询

        /// <summary>
        /// 按日查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_DaysQuery_Click(object sender, EventArgs e)
        {
            dtDays = null;
            string startDateTime = dtpDays.Value.ToString("yyyy-MM-dd 00:00:00");
            string endDateTime = dtpDays.Value.ToString("yyyy-MM-dd 23:59:59");
            dtDays = CommonMethods.db.QueryDataTable(CommonMethods.dBSQL.GetStaticByDay(startDateTime, endDateTime));
            if (dtDays != null && dtDays.Rows.Count > 0)
            {
                this.dgvDays.DataSource = null;
                this.dgvDays.DataSource = dtDays;
            }
        }

        /// <summary>
        /// 按日导出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_DaysExPort_Click(object sender, EventArgs e)
        {
            if (dgvDays.Columns.Count <= 0)
            {
                MessageBox.Show("导出失败，无查询结果");
                return;
            }

            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.FileName = $"产能统计_按日统计_{DateTime.Now.ToString("yyyyMMddHHmmss")}";
            saveFileDialog.Filter = "*|*.csv";
            if (saveFileDialog.ShowDialog() == DialogResult.Cancel)
                return;

            string msg = "";
            if (CSVHelper<object>.ExportDataTableToCSV(dtDays, saveFileDialog.FileName, out msg))
            {
                MessageBox.Show("导出成功!");
            }
        }

        #endregion

        #region 3、按周查询
        /// <summary>
        /// 按周查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_WeekQuery_Click(object sender, EventArgs e)
        {
            dtWeeks = null;
            //确定星期几
            var index = (int)dtpWeek.Value.DayOfWeek;
            index = index == 0 ? 7 : index;
            //当前周的范围
            string retStartDay = dtpWeek.Value.AddDays(-(index - 1)).ToString();
            string retEndDay = dtpWeek.Value.AddDays(7 - index).ToString();

            dtWeeks = CommonMethods.db.QueryDataTable(CommonMethods.dBSQL.GetStaticByWeek(retStartDay, retEndDay));
            if (dtWeeks != null && dtWeeks.Rows.Count > 0)
            {
                this.dgvWeek.DataSource = null;
                this.dgvWeek.DataSource = dtWeeks;
            }
        }

        /// <summary>
        /// 按周导出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_WeekExPort_Click(object sender, EventArgs e)
        {
            if (dgvWeek.Columns.Count <= 0)
            {
                MessageBox.Show("导出失败，无查询结果");
                return;
            }

            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.FileName = $"产能统计_按周统计_{DateTime.Now.ToString("yyyyMMddHHmmss")}";
            saveFileDialog.Filter = "*|*.csv";
            if (saveFileDialog.ShowDialog() == DialogResult.Cancel)
                return;

            string msg = "";
            if (CSVHelper<object>.ExportDataTableToCSV(dtWeeks, saveFileDialog.FileName, out msg))
            {
                MessageBox.Show("导出成功!");
            }
        }
        #endregion

        #region 4、按月查询
        /// <summary>
        /// 按月查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_MonthQuery_Click(object sender, EventArgs e)
        {

            dtMonths = null;
            string startDateTime = dtMonth.Value.ToString("yyyy-MM-01 00:00:00");

            string endDateTime = new DateTime(dtMonth.Value.Year, dtMonth.Value.Month, DateTime.DaysInMonth(dtMonth.Value.Year, dtMonth.Value.Month)).ToString("yyyy-MM-dd 23:59:59");//通过指定日期计算当月最后一天
            dtMonths = CommonMethods.db.QueryDataTable(CommonMethods.dBSQL.GetStaticByMonth(startDateTime, endDateTime));
            if (dtMonth != null && dtMonths.Rows.Count > 0)
            {
                this.dgvMonth.DataSource = null;
                this.dgvMonth.DataSource = dtMonths;
            }
        }

        /// <summary>
        /// 按月导出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_MonthExPort_Click(object sender, EventArgs e)
        {
            if (dgvMonth.Columns.Count <= 0)
            {
                MessageBox.Show("导出失败，无查询结果");
                return;
            }

            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.FileName = $"产能统计_按月统计_{DateTime.Now.ToString("yyyyMMddHHmmss")}";
            saveFileDialog.Filter = "*|*.csv";
            if (saveFileDialog.ShowDialog() == DialogResult.Cancel)
                return;

            string msg = "";
            if (CSVHelper<object>.ExportDataTableToCSV(dtMonths, saveFileDialog.FileName, out msg))
            {
                MessageBox.Show("导出成功!");
            }
        }

        #endregion

        #endregion


        /// <summary>
        /// 选择班次时间变更
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmb_AlarmType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmb_AlarmType.SelectedIndex == 1) //白班
            {
                DateTime baiClassStart = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd 8:30:00"));
                DateTime baiClassEnd = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd 20:29:59"));

                dtp_AlarmTimeStart.Value = baiClassStart;
                dtp_AlarmTimeEnd.Value = baiClassEnd;
            }
            else if (cmb_AlarmType.SelectedIndex == 2) //夜班
            {
                DateTime yeClassStart = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd 20:30:00"));
                DateTime yeClassEnd = Convert.ToDateTime(DateTime.Now.AddDays(1).ToString("yyyy-MM-dd 8:29:59"));

                dtp_AlarmTimeStart.Value = yeClassStart;
                dtp_AlarmTimeEnd.Value = yeClassEnd;
            }
            else
            {
                DateTime baiClassStart = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd 00:00:00"));
                DateTime baiClassEnd = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd 23:59:59"));

                dtp_AlarmTimeStart.Value = baiClassStart;
                dtp_AlarmTimeEnd.Value = baiClassEnd;
            }
        }

        /// <summary>
        /// 查询数据
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="alarmType"></param>
        /// <returns></returns>
        private OperateResult<DataTable> QueryProcess(string start, string end, string alarmType)
        {
            DateTime startDateTime = Convert.ToDateTime(start);
            DateTime endDateTime = Convert.ToDateTime(end);

            if (startDateTime >= endDateTime)
            {
                return OperateResult.CreateFailResult<DataTable>("开始时间不能大于结束时间");
            }

            TimeSpan timeSpan = endDateTime - startDateTime;

            if (timeSpan.TotalDays > 1.0)
            {
                return OperateResult.CreateFailResult<DataTable>("查询范围不能超过1天");
            }

            DataTable dataTable = CommonMethods.db.QueryDataTable(CommonMethods.dBSQL.SelectHostAlarmData(start, end, alarmType));
            if (dataTable != null)
            {
                return OperateResult.CreateSuccessResult<DataTable>(dataTable);
            }
            else
            {
                return OperateResult.CreateFailResult<DataTable>("未能查到数据，请检测");
            }
        }


        /// <summary>
        /// 报警信息查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_AlarmQuery_Click(object sender, EventArgs e)
        {
            string start = this.dtp_AlarmTimeStart.Text;
            string end = this.dtp_AlarmTimeEnd.Text;

            string alarmType = this.cmb_AlarmType.Text;

            Task<OperateResult<DataTable>> task1 = Task.Run(() =>
            {
                return QueryProcess(start, end, alarmType);
            });

            var task2 = task1.ContinueWith(task =>
            {
                this.Invoke(new Action(() =>
                {
                    if (task.Result.IsSuccess)
                    {
                        this.dgv_AlarmData.DataSource = null;
                        this.dgv_AlarmData.DataSource = task.Result.Content;
                    }
                    else
                    {
                        new FrmMsgBoxOutWithAck(2, "查询失败：" + task.Result.Message, "报警查询").Show();
                    }
                }));
            });
        }


        /// <summary>
        /// 报警信息导出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_AlarmExport_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "XLSX文件(*.xlsx)|*.xlsx|所有文件|*.*";
            saveFileDialog.Title = "导出历史报警";
            saveFileDialog.FileName = "历史报警" + DateTime.Now.ToString("yyyyMMddHHmmss");
            saveFileDialog.DefaultExt = "xlsx";
            saveFileDialog.AddExtension = true;

            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                MiniExcel.SaveAs(saveFileDialog.FileName, this.dgv_AlarmData.DataSource);

                if (new FrmMsgBoxWithAck("导出报警成功，是否立即打开？", "打开报警记录").ShowDialog() == DialogResult.OK)
                {
                    Process.Start(saveFileDialog.FileName);
                }
            }
        }

        private void dgv_AlarmData_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            DataGridViewHelper.DgvRowPostPaint((DataGridView)sender, e);
        }
    }
}
